Given positive integer n. Find
and print the square of difference between the maximum and minimum numbers,
composed from the digits of number n.
For example, if given number is 30605, the maximum number, composed
from its digits, is 65300, and minimum number is 356 (the
minimum is 00356, but leading zeros are not counted). The required square
of difference is (65300 – 356) * (65300 – 356)
= 4217723136.
Input. One positive integer n (1 ≤ n ≤ 109).
Output. Print the required square of difference.
Sample input |
Sample output |
30605 |
4217723136 |
strings
Read
the number into character array. Sort the digits in decreasing order and get
the largest number a. Sort the digits
in increasing order and get the smallest number b. Compute their squared difference.
Declare a character array.
char s[20];
Read an input string.
gets(s);
Sort the digits in decreasing order.
Convert the string to the number a.
sort(s, s + strlen(s), greater<char>());
sscanf(s, "%lld", &a);
Sort the digits in increasing order. Convert the string to the number b.
sort(s, s + strlen(s), less<char>());
sscanf(s, "%lld", &b);
Print the
required square of difference.
printf("%lld\n", (a - b) * (a
- b));
#include <iostream>
#include <set>
#include <string>
#include <algorithm>
using namespace std;
long long a, b;
string s;
int main(void)
{
cin >> s;
sort(s.begin(),
s.end(), greater<char>());
sscanf(s.c_str(),
"%lld", &a);
sort(s.begin(),
s.end(), less<char>());
sscanf(s.c_str(),
"%lld", &b);
printf("%lld\n", (a - b) * (a - b));
return 0;
}
Java realization
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
String s[] = con.nextLine().split("");
// s = {"1", "2", "3",
"4", "5", "6"}
Arrays.sort(s);
long a = Integer.parseInt(String.join("", s));
Arrays.sort(s,Collections.reverseOrder());
long b = Integer.parseInt(String.join("", s));
System.out.println((a - b) * (a - b));
con.close();
}
}